// 配置 marked.js
marked.setOptions({
    breaks: true,
    gfm: true,
    headerIds: false,
    highlight: function(code, lang) {
        if (lang && Prism.languages[lang]) {
            return Prism.highlight(code, Prism.languages[lang], lang);
        }
        return code;
    }
});

// 添加提示函数
function showToast(message, type = 'error') {
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.textContent = message;
    document.body.appendChild(toast);

    // 添加显示类以触发动画
    setTimeout(() => toast.classList.add('show'), 10);

    // 3秒后移除
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => document.body.removeChild(toast), 300);
    }, 3000);
}

// 创建 Vue 应用
const app = Vue.createApp({
    data() {
        return {
            messages: [],
            currentMessage: '',
            isProcessing: false,
            expandedMessageId: null,
            uploadedFiles: [],   // 已上传的文件列表
            voiceEnabled: false, // 是否启用语音
            avatarEnabled: false,  // 是否启用数字人
            
            // 语音状态 - 添加这些属性用于语音浮窗显示
            isVoicePlaying: false,
            voicePlayingText: '',
            isPaused: false,
            isListening: false,  // 确保默认为false

            // 添加初始化状态控制
            initialLoading: true,
            showVoicePopup: false,  // 控制语音播放弹窗显示
            showVoiceInput: false,  // 控制语音输入弹窗显示
            showFilePreview: false,  // 控制文件预览显示
            isAppReady: false  // 新增：应用是否准备就绪
        };
    },
    
    created() {
        // 在组件创建时初始化所有状态
        this.initialLoading = true;
        this.showVoicePopup = false;
        this.showVoiceInput = false;
        this.showFilePreview = false;
        this.isVoicePlaying = false;
        this.isListening = false;
        this.voiceEnabled = false;
        this.avatarEnabled = false;
        this.isAppReady = false;

        // 初始化外部模块
        if (window.FileUploader) {
            FileUploader.init();
        }
        if (window.VoicePlayer) {
            VoicePlayer.init();
        }
        if (window.AvatarPlayer) {
            AvatarPlayer.init();
        }
        if (window.VoiceInput) {
            VoiceInput.init();
        }
    },
    
    mounted() {
        // 添加欢迎消息
        this.messages.push({
            id: 'welcome-' + Date.now(),
            content: this.renderMarkdown('## 欢迎使用 AI 聊天助手\n请输入您的问题，我会尽力为您解答。'),
            isUser: false,
            timestamp: new Date().toISOString()
        });
        
        // 滚动到底部
        this.$nextTick(() => {
            this.scrollToBottom();
        });
        
        // 同步文件上传状态
        if (window.FileUploader) {
            this.uploadedFiles = [...FileUploader.data.uploadedFiles];
            this.showFilePreview = this.uploadedFiles.length > 0;
        }
        
        // 设置语音状态同步
        if (window.VoicePlayer) {
            setInterval(() => {
                this.syncVoiceStatus();
            }, 500);
        }

        // 添加数字人错误事件监听器
        document.addEventListener('avatarError', (event) => {
            if (event.detail.shouldResetSwitch) {
                this.avatarEnabled = false;
            }
            // 使用自定义提示组件显示错误
            showToast(event.detail.message);
        });

        // 处理页面卸载
        window.addEventListener('beforeunload', () => {
            if (window.AvatarPlayer) {
                AvatarPlayer.close();
            }
            if (window.VoicePlayer) {
                VoicePlayer.closeVoice();
            }
        });

        // 设置短暂延迟确保所有模块正确初始化后再显示UI
        setTimeout(() => {
            this.initialLoading = false;
            this.isAppReady = true;
        }, 300);
    },
    
    watch: {
        voiceEnabled(newVal) {
            if (window.VoicePlayer) {
                VoicePlayer.setVoiceEnabled(newVal);
            }
        },
        avatarEnabled(newVal) {
            if (window.AvatarPlayer) {
                AvatarPlayer.setEnabled(newVal);
            }
        }
    },
    
    methods: {
        // 同步语音播放器状态到UI
        syncVoiceStatus() {
            if (window.VoicePlayer) {
                const wasPlaying = this.isVoicePlaying;
                this.isVoicePlaying = VoicePlayer.data.isVoicePlaying;
                this.voicePlayingText = VoicePlayer.data.voicePlayingText;
                this.isPaused = VoicePlayer.data.isPaused;
                
                // 只有在状态真正改变时才更新弹窗显示状态
                if (this.isVoicePlaying !== wasPlaying) {
                    this.showVoicePopup = this.isVoicePlaying;
                }
            }
        },

        // 同步语音和数字人状态
        syncAvatarStatus() {
            if (this.avatarEnabled && window.AvatarPlayer && 
                (AvatarPlayer.data.isPlaying || AvatarPlayer.data.textQueue.length > 0)) {
                if (window.VoicePlayer && VoicePlayer.data.isVoicePlaying) {
                    VoicePlayer.closeVoice();
                }
            }
        },
        
        // 处理文件上传
        handleFileUpload(event) {
            if (window.FileUploader) {
                this.showFilePreview = true;
                FileUploader.handleFileUpload(event, (files) => {
                    this.uploadedFiles = [...files];
                });
            }
        },
        
        // 移除上传的文件
        removeUploadedFile(fileId) {
            if (window.FileUploader) {
                FileUploader.removeUploadedFile(fileId, (files) => {
                    this.uploadedFiles = [...files];
                    if (files.length === 0) {
                        this.showFilePreview = false;
                    }
                });
            }
        },
        
        // 移除文件
        removeFile() {
            if (window.FileUploader) {
                FileUploader.removeFile();
            }
        },
        
        // 格式化文件大小
        formatFileSize(size) {
            return window.FileUploader ? 
                FileUploader.formatFileSize(size) : 
                (size < 1024 ? size + ' B' : size < 1048576 ? (size / 1024).toFixed(2) + ' KB' : (size / 1048576).toFixed(2) + ' MB');
        },
        
        // 发送消息
        sendMessage() {
            if (this.isProcessing || (!this.currentMessage.trim() && (!window.FileUploader || FileUploader.data.uploadedFiles.length === 0))) {
                return;
            }
            
            const userMessage = this.currentMessage.trim();
            this.currentMessage = '';
            this.isProcessing = true;
            
            let userContent = userMessage;
            
            if (window.FileUploader && FileUploader.data.uploadedFiles.length > 0) {
                userContent += '<div class="file-references">';
                for (const file of FileUploader.data.uploadedFiles) {
                    userContent += `<div class="file-reference">已引用文件: ${file.name} (${this.formatFileSize(file.size)})</div>`;
                }
                userContent += '</div>';
            }
            
            const userMsgId = 'user-' + Date.now();
            this.messages.push({
                id: userMsgId,
                content: userContent,
                isUser: true,
                timestamp: new Date().toISOString(),
                originalInput: userMessage,
            });
            
            const thinkingMsgId = 'thinking-' + Date.now();
            this.messages.push({
                id: thinkingMsgId,
                content: '<div class="thinking-indicator"><div class="spinner"></div><span>AI 正在思考中...</span></div>',
                isUser: false,
                timestamp: new Date().toISOString(),
                thinking: true
            });
            
            this.scrollToBottom();
            
            const formData = new FormData();
            formData.append('userInput', userMessage);
            
            if (window.FileUploader && FileUploader.data.uploadedFiles.length > 0) {
                const fileIds = FileUploader.data.uploadedFiles.map(file => file.id);
                formData.append('fileIds', JSON.stringify(fileIds));
            }
            
            fetch('/api/chat/assistant', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const thinkingIndex = this.messages.findIndex(msg => msg.id === thinkingMsgId);
                if (thinkingIndex !== -1) {
                    this.messages.splice(thinkingIndex, 1);
                }
                
                const aiMessageId = 'ai-' + Date.now();
                let aiResponse = '';
                this.messages.push({
                    id: aiMessageId,
                    content: '',
                    isUser: false,
                    timestamp: new Date().toISOString(),
                    thinking: true
                });
                
                const reader = response.body.getReader();
                const decoder = new TextDecoder("utf-8");
                let buffer = '';
                
                const processStream = () => {
                    reader.read().then(({ done, value }) => {
                        if (done) {
                            this.isProcessing = false;
                            
                            if (this.voiceEnabled && window.VoicePlayer) {
                                VoicePlayer.flushVoiceBuffer();
                            }
                            
                            const index = this.messages.findIndex(msg => msg.id === aiMessageId);
                            if (index !== -1) {
                                this.messages[index].thinking = false;
                                
                                this.$nextTick(() => this.applyCodeHighlight());
                            }
                            return;
                        }
                        
                        const chunk = decoder.decode(value, { stream: true });
                        const lines = (buffer + chunk).split('\n');
                        
                        buffer = lines.pop() || '';
                        
                        for (const line of lines) {
                            if (line.trim() === '') continue;
                            
                            if (line.startsWith('data:')) {
                                try {
                                    const jsonData = JSON.parse(line.substring(5).trim());
                                    
                                    if (jsonData.content) {
                                        aiResponse += jsonData.content;
                                        
                                        const index = this.messages.findIndex(msg => msg.id === aiMessageId);
                                        if (index !== -1) {
                                            this.messages[index].content = this.renderMarkdown(aiResponse);
                                            
                                            if (jsonData.content) {
                                                this.handleAIResponse(jsonData.content, aiMessageId);
                                            }
                                        }
                                        
                                        this.$nextTick(() => {
                                            this.scrollToBottom();
                                            this.applyCodeHighlight();
                                        });
                                    }
                                } catch (e) {
                                }
                            }
                        }
                        
                        processStream();
                    }).catch(error => {
                        this.isProcessing = false;
                        
                        const index = this.messages.findIndex(msg => msg.id === aiMessageId);
                        if (index !== -1) {
                            this.messages[index].thinking = false;
                            if (!this.messages[index].content) {
                                this.messages[index].content = '<div class="error-message">读取响应失败，请重试</div>';
                            }
                        }
                    });
                };
                
                processStream();
            })
            .catch(error => {
                this.isProcessing = false;
                
                const thinkingIndex = this.messages.findIndex(msg => msg.id === thinkingMsgId);
                if (thinkingIndex !== -1) {
                    this.messages[thinkingIndex].content = '<div class="error-message">连接服务器失败，请稍后重试</div>';
                    this.messages[thinkingIndex].thinking = false;
                }
            });
            
            if (window.FileUploader) {
                FileUploader.clearUploadedFiles();
                this.uploadedFiles = [];
            }
        },
        
        // 渲染 Markdown
        renderMarkdown(text) {
            if (!text) return '';
            
            try {
                return marked.parse(String(text));
            } catch (e) {
                return `<pre>${String(text)}</pre>`;
            }
        },
        
        // 应用代码高亮
        applyCodeHighlight() {
            document.querySelectorAll('pre code').forEach((block) => {
                Prism.highlightElement(block);
            });
        },
        
        // 滚动到底部
        scrollToBottom() {
            const chatBox = document.getElementById('chatBox');
            if (chatBox) {
                chatBox.scrollTop = chatBox.scrollHeight;
            }
        },
        
        // 复制消息
        copyMessage(message) {
            const tempTextArea = document.createElement('textarea');
            tempTextArea.value = message.content.replace(/<[^>]*>/g, '');
            document.body.appendChild(tempTextArea);
            tempTextArea.select();
            document.execCommand('copy');
            document.body.removeChild(tempTextArea);
            
            alert('复制成功！');
        },
        
        // 点赞消息
        likeMessage(message) {
            if (!message.isUser) {
                message.liked = !message.liked;
                if (message.liked) {
                    message.disliked = false;
                }
            }
        },
        
        // 不喜欢消息
        dislikeMessage(message) {
            if (!message.isUser) {
                message.disliked = !message.disliked;
                if (message.disliked) {
                    message.liked = false;
                }
            }
        },
        
        // 重试消息
        retryMessage(message) {
            if (this.isProcessing) return;
            
            let userMessage = null;
            for (let i = this.messages.length - 1; i >= 0; i--) {
                if (this.messages[i].isUser && this.messages[i].originalInput) {
                    userMessage = this.messages[i];
                    break;
                }
            }
            
            if (userMessage && userMessage.originalInput) {
                this.currentMessage = userMessage.originalInput;
                this.sendMessage();
            } else {
                alert('无法找到原始问题，请重新输入');
            }
        },
        
        // 处理键盘事件
        handleKeyDown(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                this.sendMessage();
            }
        },
        
        // 创建新聊天
        createNewChat() {
            this.messages = [];
            
            this.messages.push({
                id: 'welcome-' + Date.now(),
                content: this.renderMarkdown('## 欢迎使用 AI 聊天助手\n请输入您的问题，我会尽力为您解答。'),
                isUser: false,
                timestamp: new Date().toISOString()
            });
            
            if (window.FileUploader) {
                FileUploader.clearUploadedFiles();
                this.uploadedFiles = [];
            }
        },
        
        // 展开/收起消息
        expandMessage(message) {
            if (this.expandedMessageId === message.id) {
                this.expandedMessageId = null;
            } else {
                this.expandedMessageId = message.id;
            }
            this.$nextTick(() => {
                this.scrollToBottom();
            });
        },
        
        // 关闭语音控制
        closeVoice() {
            if (window.VoicePlayer) {
                VoicePlayer.closeVoice();
                this.syncVoiceStatus();
                this.showVoicePopup = false;
            }
        },
        
        // 切换语音暂停状态
        toggleVoicePause() {
            if (window.VoicePlayer) {
                VoicePlayer.toggleVoicePause();
                this.syncVoiceStatus();
            }
        },

        // 处理AI回复时，决定使用数字人还是语音播报
        handleAIResponse(text, messageId) {
            if (this.avatarEnabled && window.AvatarPlayer) {
                AvatarPlayer.speak(text);
            } else if (this.voiceEnabled && window.VoicePlayer) {
                VoicePlayer.handleTextChunk(text, messageId);
            }
        },
        
        // 切换数字人状态
        toggleAvatar() {
            this.avatarEnabled = !this.avatarEnabled;
        },

        // 切换语音输入功能
        toggleVoiceInput() {
            if (!window.VoiceInput) return;
            
            if (VoiceInput.isActive()) {
                // 如果正在监听，则停止
                VoiceInput.stopListening();
                this.isListening = false;
                this.showVoiceInput = false;
            } else {
                // 否则开始监听
                const success = VoiceInput.startListening(
                    (interimResult, finalResult) => {
                        if (finalResult) {
                            this.currentMessage = finalResult;
                        }
                    },
                    (finalResult) => {
                        if (finalResult) {
                            this.currentMessage = finalResult;
                            this.isListening = false;
                            this.showVoiceInput = false;
                        }
                    }
                );
                
                this.isListening = success;
                this.showVoiceInput = success;
            }
        }
    }
});

// 挂载 Vue 应用
app.mount('#app');